package com.example.zbh.dsliao.ui.fragment;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.presenter.BasePresenter;
import com.example.zbh.dsliao.ui.activty.CharActivity;
import com.example.zbh.dsliao.ui.activty.GroupChatActivity;
import com.example.zbh.dsliao.ui.activty.MVPBaseActivity;
import com.example.zbh.dsliao.ui.adapter.ConversartionListAdapter;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.view.CustomChangeDialog;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;



/**
 * 会话列表fragment
 */
public class ConversarionListFragment extends MVPBaseFragment implements ConversartionListAdapter.OnItemLongClickListenerConversartion, TextWatcher, View.OnClickListener, View.OnTouchListener, EMEventListener {
    private LinearLayout back;

    private ListView listView;
    private ConversartionListAdapter adapter;
    private Handler handler;
    private LinearLayout deleteContactionlist;
    private int position;
    //新消息铃声
    private SoundPool soundPool;
    private int soundId;
    //未读消息总数
    private int unReadMessageCount = 0;

    //搜索框
    private EditText queryConversation;
    private ImageView queryDeleteBtn;

    private PreferenceHelper preferenceHelper;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            onRefresh();
        }
    };


    //初始化指挥家
    @Override
    protected BasePresenter createPresenter() {
        return new BasePresenter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    /**
     * 监听mainactivity的eventbus发过来的的状态
     * (包括 1 == 账号被服务器删除
     * 2 == 账号被别的设备登录)
     **/
    public void onEventMainThread(Integer data) {
        if (data == 102) {
            DliaoUtils.showDialogConnection(getActivity());
        } else if (data == 101) {
            DliaoUtils.showDialogUserRemoved(getActivity());
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_conversartionlist, null);
        listView = (ListView) v.findViewById(R.id.conversartionlistView);
        //搜索框
        queryConversation = (EditText) v.findViewById(R.id.queryConversation);
        queryDeleteBtn = (ImageView) v.findViewById(R.id.queryDeleteBtn);
        back = (LinearLayout) v.findViewById(R.id.back);
        return v;
    }

    //控件监听及其他
    @Override
    protected void initData() {
        back.setVisibility(View.GONE);
        preferenceHelper = PreferenceHelper.getInstance();

        //新消息铃声初始化
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundId = soundPool.load(getActivity(), R.raw.fallbackring, 1);

        handler = new Handler();

        adapter = new ConversartionListAdapter(getActivity());
        listView.setAdapter(adapter);
        adapter.addData(loadConversationList());
        Log.i("sdsdsdsdsdsdd", "adapter.addData(loadConversationList())");


        adapter.setOnItemLongClickListenerConversartion(this);

        queryConversation.addTextChangedListener(this);
        queryDeleteBtn.setOnClickListener(this);
        listView.setOnTouchListener(this);


        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck});
    }


    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        handler.post(runnable);
        Log.d("zainali", "来没来啊>>>>>>>>>");

        //查看用户设置是否开启新消息铃声提醒
        boolean isChange = preferenceHelper.getNewNotify();
        if (isChange == true) {
            //播放铃声
            soundPool.play(soundId, 1, 1, 3, 1, 0);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.queryDeleteBtn://搜索框的清除按钮
                queryConversation.getText().clear();
                hideSoftKeyboard();
                queryDeleteBtn.setVisibility(View.INVISIBLE);
                handler.postDelayed(runnable, 200);
                break;
        }
    }


    /**
     * edittext监听
     **/
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (s.length() > 0) {
            queryDeleteBtn.setVisibility(View.VISIBLE);
        } else {
            queryDeleteBtn.setVisibility(View.INVISIBLE);
        }
        Log.d("ConversarionListFragmen", "beforeTextChanged" + ">>>>>" + s);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.d("ConversarionListFragmen", "onTextChanged" + ">>>>" + s);
    }

    @Override
    public void afterTextChanged(Editable s) {
        adapter.getFilter().filter(s);//过滤器
        //s == null 和 s.length == 0是两回事
        if (s.length() == 0) {
            queryDeleteBtn.setVisibility(View.INVISIBLE);
            handler.postDelayed(runnable, 200);
            Log.d("ConversarionListFragmen", "afterTextChanged" + ">>>>>>" + s);
        }
    }


    /**
     * listview触碰事件
     * (防止正在搜索时点击联系人键盘没有消失)
     **/
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        hideSoftKeyboard();//隐藏键盘
        return false;
    }


    @Override
    public void onResume() {
        super.onResume();
        handler.postDelayed(runnable, 200);
    }


    /**
     * 获取会话列表
     **/
    protected List<EMConversation> loadConversationList() {
        //获取所有会话
        Hashtable<String, EMConversation> conversationHashtabl = EMChatManager.getInstance().getAllConversations();


        //过滤掉message size为0的conversation
        /**
         * 如果在排序过程中收到新消息, lastMsgTime会发生变化
         * 影响排序过程, Collection.sort会产生异常
         * 保证conversation在sort过程中最后一条消息时间不变
         * 避免并发问题
         * **/
        List<Pair<Long, EMConversation>> pairList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversationHashtabl) {
            for (EMConversation conversation : conversationHashtabl.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    pairList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    int unRead = conversation.getUnreadMsgCount();
                    unReadMessageCount = unReadMessageCount + unRead;
                }
            }
        }

        //发送
        EventBus.getDefault().post(unReadMessageCount);
        unReadMessageCount = 0;
        sortConversationByLastChatTime(pairList);
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> pair : pairList) {
            list.add(pair.second);
        }
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     **/
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> pairList) {
        Collections.sort(pairList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(Pair<Long, EMConversation> lhs, Pair<Long, EMConversation> rhs) {
                if (lhs.first == rhs.first) {
                    return 0;
                } else if (rhs.first > lhs.first) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }


    /**
     * item点击事件 长按,短按
     **/
    @Override
    public void onlongclick(View view, int code, int position) {
        this.position = position;
        Log.d("shshshshshshshs", "onlongclick() called with: " + "view = [" + view + "], code = [" + code + "], position = [" + position + "]");

        //短按跳转到对应聊天页面
        if (code == 1) {
            unReadMessageCount = 0;
            EMConversation conversation = loadConversationList().get(position);
            //获取所有会话的未读数量
            Hashtable<String, EMConversation> conversationHashtabl = EMChatManager.getInstance().getAllConversations();
            List<Pair<Long, EMConversation>> pairList = new ArrayList<Pair<Long, EMConversation>>();
            synchronized (conversationHashtabl) {
                for (EMConversation conversationnow : conversationHashtabl.values()) {
                    if (conversationnow.getAllMessages().size() != 0) {
                        int unRead = conversationnow.getUnreadMsgCount();
                        unReadMessageCount = unReadMessageCount + unRead;
                    }
                }
                //点击之后减掉当前点击的会话的未读数
                unReadMessageCount = unReadMessageCount - conversation.getUnreadMsgCount();
                //发送
                EventBus.getDefault().post(unReadMessageCount);
            }
            //消息未读数回执给服务器 下次再取未读时这一条就为0
            conversation.markAllMessagesAsRead();

            String name = conversation.getUserName();
            Log.i("mnnnnnnnnnnnnnnn", ">>>>>>>>>>>>>>>>>>" + name);
            if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {

                EMGroup emGroup = EMGroupManager.getInstance().getGroup(name);
                String groupName = emGroup != null ? emGroup.getGroupId() : name;
                Intent intent = new Intent();
                intent.putExtra("userId", groupName);
                intent.putExtra("Groupname", emGroup.getGroupName());
                intent.setClass(getActivity(), GroupChatActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent();
                intent.putExtra("userName", name);
                intent.setClass(getActivity(), CharActivity.class);
                startActivity(intent);
            }
        } else if (code == 2) {
            //长按弹出dialog
            showDialog();
        }
    }


    /**
     * 长按弹出dialog
     ****/
    private void showDialog() {
        final CustomChangeDialog customChangeDialog = new CustomChangeDialog(getActivity(), "请选择", View.GONE, "", "删除本条会话", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        customChangeDialog.dismiss();
                        EMConversation conversation = (EMConversation) listView.getAdapter().getItem(position);
                        //删除此会话
                        EMChatManager.getInstance().deleteConversation(conversation.getUserName(), conversation.getIsGroup(), true);
                        onRefresh();
                        Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.cancleBtn:
                        customChangeDialog.dismiss();
                        break;
                }
            }
        });

    }


    //刷新
    private void onRefresh() {
        adapter.addData(loadConversationList());
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Log.i("sdsdsdsdsdsdd", "true");
        } else {
            Log.i("sdsdsdsdsdsdd", "false");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("sdsdsdsdsdsdd", "onDestroy()");
        EMChatManager.getInstance().unregisterEventListener(this);
        EventBus.getDefault().unregister(this);
        //销毁铃声
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
    }

}
